// +----------------------------------------------------------------------
// | JavaWeb_EleVue_Pro前后端分离旗舰版框架 [ JavaWeb ]
// +----------------------------------------------------------------------
// | 版权所有 2021 上海JavaWeb研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.javaweb.vip/
// +----------------------------------------------------------------------
// | 作者: 鲲鹏 <javaweb520@gmail.com>
// +----------------------------------------------------------------------
// | 免责声明:
// | 本软件框架禁止任何单位和个人用于任何违法、侵害他人合法利益等恶意的行为，禁止用于任何违
// | 反我国法律法规的一切平台研发，任何单位和个人使用本软件框架用于产品研发而产生的任何意外
// | 、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、附带
// | 或衍生的损失等)，本团队不承担任何法律责任。本软件框架只能用于公司和个人内部的法律所允
// | 许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

package com.javaweb.admin.service.impl;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.javaweb.admin.entity.File;
import com.javaweb.admin.entity.IdentifyData;
import com.javaweb.admin.mapper.IdentifyDataMapper;
import com.javaweb.common.utils.*;
import com.javaweb.common.common.BaseQuery;
import com.javaweb.common.common.BaseServiceImpl;
import com.javaweb.admin.entity.Identify;
import com.javaweb.admin.mapper.IdentifyMapper;
import com.javaweb.admin.query.IdentifyQuery;
import com.javaweb.admin.service.IIdentifyService;
import com.javaweb.system.entity.Article;
import com.javaweb.system.mapper.ArticleMapper;
import com.javaweb.admin.vo.identify.IdentifyInfoVo;
import com.javaweb.admin.vo.identify.IdentifyListVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.*;

/**
 * <p>
 * 识别记录表 服务类实现
 * </p>
 *
 * @author 鲲鹏
 * @since 2023-09-01
 */
@Service
public class IdentifyServiceImpl extends BaseServiceImpl<IdentifyMapper, Identify> implements IIdentifyService {

    @Autowired
    private IdentifyMapper identifyMapper;
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private IdentifyDataMapper identifyDataMapper;

    /**
     * 获取数据列表
     *
     * @param query 查询条件
     * @return
     */
    @Override
    public JsonResult getList(BaseQuery query) {
        IdentifyQuery identifyQuery = (IdentifyQuery) query;
        // 查询条件
        QueryWrapper<Identify> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mark", 1);
        queryWrapper.orderByDesc("id");

        // 获取数据列表
        IPage<Identify> page = new Page<>(identifyQuery.getPage(), identifyQuery.getLimit());
        IPage<Identify> pageData = identifyMapper.selectPage(page, queryWrapper);
        pageData.convert(x -> {
            IdentifyListVo identifyListVo = Convert.convert(IdentifyListVo.class, x);

            return identifyListVo;
        });
        return JsonResult.success(pageData);
    }

    /**
     * 获取详情Vo
     *
     * @param id 记录ID
     * @return
     */
    @Override
    public Object getInfo(Serializable id) {
        Identify entity = (Identify) super.getInfo(id);
        // 返回视图Vo
        IdentifyInfoVo identifyInfoVo = new IdentifyInfoVo();
        // 拷贝属性
        BeanUtils.copyProperties(entity, identifyInfoVo);

        return identifyInfoVo;
    }

    /**
     * 添加、更新记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    public JsonResult edit(Identify entity) {
        // 

        if (StringUtils.isNotNull(entity.getId()) && entity.getId() > 0) {
        } else {
        }
        return super.edit(entity);
    }

    /**
     * 删除记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    public JsonResult delete(Identify entity) {
        entity.setMark(0);
        return super.delete(entity);
    }

    @Override
    public JsonResult shibie(File files) {
        Map<String, String> file = new HashMap<String, String>();
        file.put("file", files.getUrl());
        //file.put("file", "http://111.59.35.125:9034/api/images/identify/20231019/20231019142530734.jpg");
        Integer cateId = 4;
        String url = "http://pest.gxfsdc.com.cn:8081/Pest";
        if(files.getType()==2){
            url = "http://pest.gxfsdc.com.cn:8082/CamelliaDisease";
            cateId = 5;
        }
        String rspStr = HttpClientUtil.postParams(url, file);
        if (org.springframework.util.StringUtils.isEmpty(rspStr)) {
            return JsonResult.error("识别失败");
        }

        Identify identify = new Identify();
        identify.setIdentifyJson(rspStr);
        identify.setCateId(cateId);
        identify.setUrl(files.getUrl());
        identify.setLatitude(files.getLatitude());
        identify.setLongitude(files.getLongitude());
        identify.setCreateTime(new Date());
        if(!StringUtils.isEmpty(files.getLatitude()) && !StringUtils.isEmpty(files.getLongitude())){
            String weatherUrl = "https://devapi.qweather.com/v7/weather/now?location=" + files.getLongitude() + "," +files.getLatitude() + "&key=a786d15551e24a71af09a2bde589e0c4";
            String weatherRes = HttpClientUtil.get(weatherUrl);
            JSONObject weatherResObj = JSONObject.parseObject(weatherRes);
            if(!StringUtils.isEmpty(weatherResObj.getString("now"))){
                identify.setWeather(weatherResObj.getString("now"));
            }
        }
        identifyMapper.insert(identify);
        Integer id = identify.getId();
        JSONObject obj = new JSONObject();
        JSONObject obj1 = JSONObject.parseObject(rspStr);
        IdentifyData identifyData = new IdentifyData();
        for (int i = 1; i < obj1.size() + 1; i++) {
            String data = obj1.getString(String.valueOf(i));
            String[] dataInfo = data.split(",");
            JSONObject data1 = new JSONObject();
            data1.put("name", dataInfo[0]);
            data1.put("like", dataInfo[1]);
            data1.put("x1", dataInfo[2]);
            data1.put("y1", dataInfo[3]);
            data1.put("x2", dataInfo[4]);
            data1.put("y2", dataInfo[5]);
            if(id>0){
                identifyData.setLikes(dataInfo[1]);
                identifyData.setPid(id);
                identifyData.setName(dataInfo[0]);
                identifyData.setX1(Integer.valueOf(dataInfo[2]));
                identifyData.setY1(Integer.valueOf(dataInfo[3]));
                identifyData.setX2(Integer.valueOf(dataInfo[4]));
                identifyData.setY2(Integer.valueOf(dataInfo[5]));
                identifyData.setCreateTime(new Date());
                identifyData.setMark(1);
                identifyDataMapper.insert(identifyData);
            }


            if(obj.size()>0){
                obj.put(String.valueOf(obj.size()),data1);
            }else{
                obj.put(String.valueOf(i-1),data1);
            }
        }

        /*
        String rspStr = HttpClientUtil.postParams("http://pest.gxfsdc.com.cn:8081/Pest", file);
        String rspStr2 = HttpClientUtil.postParams("http://pest.gxfsdc.com.cn:8082/CamelliaDisease", file);
        JSONObject obj1 = JSONObject.parseObject(rspStr);
        JSONObject obj2 = JSONObject.parseObject(rspStr2);
        JSONObject obj = new JSONObject();
        if (obj1.size() > 0) {
            for (int i = 1; i < obj1.size() + 1; i++) {
                String data = obj1.getString(String.valueOf(i));
                String[] dataInfo = data.split(",");
                JSONObject data1 = new JSONObject();
                data1.put("name", dataInfo[0]);
                data1.put("like", dataInfo[1]);
                data1.put("x1", dataInfo[2]);
                data1.put("y1", dataInfo[3]);
                data1.put("x2", dataInfo[4]);
                data1.put("y2", dataInfo[5]);
                if(obj.size()>0){
                    obj.put(String.valueOf(obj.size()),data1);
                }else{
                    obj.put(String.valueOf(i-1),data1);
                }
            }
        }
        if (obj2.size() > 0) {
            for (int i = 1; i < obj2.size() + 1; i++) {
                String data = obj2.getString(String.valueOf(i));
                String[] dataInfo = data.split(",");
                JSONObject data2 = new JSONObject();
                data2.put("name", dataInfo[0]);
                data2.put("like", dataInfo[1]);
                data2.put("x1", dataInfo[2]);
                data2.put("y1", dataInfo[3]);
                data2.put("x2", dataInfo[4]);
                data2.put("y2", dataInfo[5]);
                if(obj.size()>0){
                    obj.put(String.valueOf(obj.size()),data2);
                }else{
                    obj.put(String.valueOf(i-1),data2);
                }

            }
        }
         */

        return JsonResult.success(obj,"识别成功");
    }

    @Override
    public JsonResult getBhInfo(File files) {

        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("title", files.getName());
        List<Article> info = articleMapper.selectList(queryWrapper);
        if(org.springframework.util.StringUtils.isEmpty(info)) {
            return JsonResult.error("未找到相关数据");
        }
        return JsonResult.success(info.get(0),"识别成功");
    }

    @Override
    public JsonResult getAddress(File files) {

        String url = "https://apis.map.qq.com/ws/geocoder/v1/?location="+files.getLatitude()+","+files.getLongitude()+"&key=PF5BZ-443LW-CFJRG-32WNP-RO5OQ-RPFRI&get_poi=1";
        String rspStr = HttpClientUtil.get(url);
        JSONObject obj = JSONObject.parseObject(rspStr);
        return JsonResult.success(obj);
    }
    @Override
    public JsonResult getTotal() {

        QueryWrapper<Identify> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cate_id",4);
        Integer chCount = identifyMapper.selectCount(queryWrapper);
        QueryWrapper<Identify> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("cate_id",5);
        Integer bhCount = identifyMapper.selectCount(queryWrapper2);
        JSONObject obj = new JSONObject();
//        obj.put("chCount",chCount);
//        obj.put("bhCount",bhCount);
        obj.put("chCount",0);
        obj.put("bhCount",0);

        return JsonResult.success(obj);
    }

    @Override
    public JsonResult setDataList() {

        QueryWrapper<Identify> queryWrapper = new QueryWrapper<>();
        List<Identify> list = identifyMapper.selectList(queryWrapper);
        for (Identify info : list) {
            JSONObject obj1 = JSONObject.parseObject(info.getIdentifyJson());
            IdentifyData identifyData = new IdentifyData();
            for (int i = 1; i < obj1.size() + 1; i++) {
                String data = obj1.getString(String.valueOf(i));
                String[] dataInfo = data.split(",");
                    identifyData.setLikes(dataInfo[1]);
                    identifyData.setId(info.getId());
                    identifyData.setName(dataInfo[0]);
                    identifyData.setX1(Integer.valueOf(dataInfo[2]));
                    identifyData.setY1(Integer.valueOf(dataInfo[3]));
                    identifyData.setX2(Integer.valueOf(dataInfo[4]));
                    identifyData.setY2(Integer.valueOf(dataInfo[5]));
                    identifyData.setCreateTime(new Date());
                    identifyData.setMark(1);
                    identifyDataMapper.insert(identifyData);
                }
            }

        return JsonResult.success();
    }


}